package com.pz.cloud.framework.society.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.cloud.framework.base.dao.CommonDao;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import com.pz.cloud.framework.base.service.BaseServiceImpl;
import com.pz.cloud.framework.business.society.entity.OrgSociety;
import com.pz.cloud.framework.business.society.entity.OrgSocietyUser;
import com.pz.cloud.framework.business.society.service.IOrgSocietyService;
import com.pz.cloud.framework.business.society.service.IOrgSocietyUserService;
import com.pz.cloud.framework.business.student.entity.Student;
import com.pz.cloud.framework.business.volunteerTeam.entity.VolunteerTeamUser;
import com.pz.cloud.framework.business.workflow.annotation.Workflow;
import com.pz.cloud.framework.business.workflow.entity.WaitDone;
import com.pz.cloud.framework.business.workflow.enums.WorkflowEnum;
import com.pz.cloud.framework.business.workflow.service.IWaitDoneService;
import com.pz.cloud.framework.model.AbstractSqlBuilder;
import com.pz.cloud.framework.model.SqlBuilder;
import com.pz.cloud.framework.model.SqlQueryGenerator;
import com.pz.cloud.framework.society.callback.OrgSocietyCallback;
import com.pz.cloud.framework.society.mapper.OrgSocietyMapper;
import com.pz.cloud.framework.util.BeanUpdateUtils;
import com.pz.cloud.framework.util.BizUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.enums.DataScope;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @Author: jeecg-boot
 * @Date: 2019-09-19
 * @Version: V1.0
 */
@Service
@Transactional
public class OrgSocietyServiceImpl extends BaseServiceImpl<OrgSocietyMapper, OrgSociety> implements IOrgSocietyService {
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private IOrgSocietyUserService orgSocietyUserService;

    @Workflow(callback = OrgSocietyCallback.class)
    public boolean save(OrgSociety entity) {
        boolean flag ;
        if(StringUtils.isEmpty(entity.getId())) {
            if (CollectionUtils.isNotEmpty(findByName(entity.getName()))) {
                throw new CustomRuntimeException("该社团已存在");
            }
            flag = super.save(entity);
        }else{
            flag = super.updateById(entity,true);
        }
        entity.getWorkflowModel().setHandlerId(entity.getInstructorId());
        OrgSocietyUser orgSocietyUser = orgSocietyUserService.findByUserIdAndSocietyId( entity.getResponsibleManId(),entity.getId());
        if(orgSocietyUser!=null){
            orgSocietyUser.setIsDirector(1);
        }else{
            orgSocietyUser = new OrgSocietyUser();
            orgSocietyUser.setUserId(entity.getResponsibleManId());
            orgSocietyUser.setRealname(entity.getResponsibleMan());
            orgSocietyUser.setActStatus(10);
            orgSocietyUser.setIsDirector(1);
            orgSocietyUser.setSocietyId(entity.getId());
        }
        orgSocietyUserService.save(orgSocietyUser);
        return flag;
    }

    @Override
    public IPage<OrgSociety> findPage(OrgSociety entity) {
        AbstractSqlBuilder sqlBuilder = SqlBuilder.init("select os.*,s.college,s.major,s.grade,s.clazz from ").appendTable(entityClass).append(" os ")
                .append("left join ").appendTable(Student.class).append(" s on os.responsible_man_id = s.user_id and s.del_flag = 0 ")
                .joinCondition(entity, "os")
                .filterDataScope("os")
                .page(entity)
                .returnType(entityClass)
                .orderBy("os.create_time desc");
        if(entity.getIsFinished()!=null){
            if(entity.getIsFinished()==0){
                sqlBuilder.append(" and act_status < :actStatus").setParms("actStatus", WorkflowEnum.ProcessStatus.流程结束.getStatus());
            }else if(entity.getIsFinished()==1){
                sqlBuilder.append(" and act_status = :actStatus").setParms("actStatus", WorkflowEnum.ProcessStatus.流程结束.getStatus());
            }
        }

        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public List<OrgSociety> findByName(String name) {
        LambdaQueryWrapper<OrgSociety> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrgSociety::getName,name);
        return list(queryWrapper);
    }

    @Override
    public boolean removeById(Serializable id) {
        checkUser(id);
        return super.removeById(id);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        idList.forEach(this::checkUser);
        return super.removeByIds(idList);
    }

    private void checkUser(Serializable id) {
        LambdaQueryWrapper<OrgSocietyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgSocietyUser::getSocietyId, id);
        if (orgSocietyUserService.count(wrapper) > 0) {
            throw new CustomRuntimeException("请先删除成员");
        }
    }

}
